
import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
	List<Client> clients = new ArrayList<Client>();
	public static void main(String[] args) {
		new ChatServer().start();
	}
	
	public void start() {
		boolean started = false;
		Socket s = null;
		ServerSocket ss = null;
		try {
			ss = new ServerSocket(6666);
			started = true;
			while(started) {
				s = ss.accept();
				Client c = new Client(s);
				new Thread(c).start();
				clients.add(c);
				System.out.println("one client connected!");
			}
		}catch(IOException e){
			//System.out.println("client disconneted!");
			e.printStackTrace();
		}finally{
			try {
				ss.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	
	class Client implements Runnable {
		private Socket s = null;
		DataInputStream dis = null;
		DataOutputStream dos = null;
		boolean bConnected = false;
		Client c = null;
		
		public Client(Socket s){
			this.s = s;
			try {
				dis = new DataInputStream(s.getInputStream());
				dos = new DataOutputStream(s.getOutputStream());
				bConnected = true;
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}
		
		public void send(String str) {
				try {
					dos.writeUTF(str);
				} catch (IOException e) {
					clients.remove(this);
					System.out.println("remove client successfully!!");
					//e.printStackTrace();
				}	
		}
		
		public void run() {
			
			try{
				while(bConnected) {
					String str = dis.readUTF();
					for(int i=0;i<clients.size();i++){
						c = clients.get(i);
						c.send(str);
					}
//System.out.println(str);
				}
			}catch (IOException e) {
				System.out.println("one client disconnected!");
			}finally{
				try {
					if(dis != null) dis.close();
					if(dos != null) dos.close();
					if(s != null) s.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
